package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 带重试机制
 *
 * @author yangyunjiao
 */
public class RetryWithTimeoutExample {
    private static final AtomicInteger attemptCount = new AtomicInteger(0);

    public static String unreliableService() throws InterruptedException {
        int attempt = attemptCount.incrementAndGet();
        Thread.sleep(1000);

        // 模拟前两次失败，第三次成功
        if (attempt < 3) {
            throw new RuntimeException("服务暂时不可用");
        }

        return "服务调用成功，尝试次数: " + attempt;
    }

    public static void main(String[] args) {
        TimeLimiter timeLimiter = SimpleTimeLimiter.create(
                Executors.newCachedThreadPool()
        );

        int maxRetries = 3;
        for (int i = 0; i < maxRetries; i++) {
            try {
                String result = timeLimiter.callWithTimeout(RetryWithTimeoutExample::unreliableService, 2, TimeUnit.SECONDS);

                System.out.println("成功: " + result);
                break; // 成功则退出循环
            } catch (TimeoutException e) {
                System.out.println("第 " + (i + 1) + " 次尝试超时");
            } catch (Exception e) {
                System.out.println("第 " + (i + 1) + " 次尝试失败: " + e.getMessage());
            }

            if (i == maxRetries - 1) {
                System.out.println("所有重试都失败了");
            }
        }
    }
}
